package plus.run;


public class Label {
		static enum State {NEW, FORWARD, POSTED};
		Label.State state = State.NEW;
		int head;
		static int ls;
		int n = ls++;
		public void Jcc(boolean when) { Emit.asm(when ? VM.JTR : VM.JFL); this.asm(); }
		public void JMP() { Emit.asm(VM.JMP); this.asm(); }
		public void JSR() { Emit.asm(VM.CUP); this.asm(); }
		public void asm() {
//			System.out.println("<< Label "+n);
			switch (state) {
			case NEW:
				head = Emit.org;
				state = State.FORWARD;
				Emit.asm16(head);
				break;
			case FORWARD:
				Emit.asm16(head);
				head = Emit.org-2;
				break;
			case POSTED:
				Emit.asm16(head);
			}
		}
		public void post() {
//			System.out.println(">>> Label "+n+":");
			switch(state) {
			case FORWARD: // There is at least one placeholder to update.
				while (true) {
					int link = VM.u16(head);
					VM.stuff16(head, Emit.org);
					if (link == head) break; // for that was the last one
					head = link; // otherwise there are more
				}
			case NEW:
				head = Emit.org;
				state = State.POSTED;
			case POSTED:
			}
		}
	}